<?php
namespace app\appletsapi\controller;

use app\common\service\Wechat;
use app\common\model\User;
use plug\SUtil;
use think\Exception;

class Login extends Base
{
//	/**
//	 * @route('applets/Authorize','get')
//	 * 获取公众号授权链接
//	 */
	public function Authorize(){
		$url = input('get.url');
		$this->result(Wechat::GetAuthorizeUrl($url),1,'操作成功');
	}

	/**
	 * @route('applets/abc')
	 * 获取公众号授权链接
	 */
	public function abc(){
		$code = input('get.code');
		echo $code;die;
	}

//	/**
//	 * @route('applets/Authlogin','post')
//	 * 通过 code 换取网页授权信息
//	 */
	public function Authlogin() {
		$code = input('post.code');
		if(!$code){
			$this->result([],-1,'404');
		}

		//通过 code 换取网页授权access_token和openid
		//这里通过 code 换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同
        try{
            $AuthorizeInfo = Wechat::AuthorizeInfo($code);
            if(!$AuthorizeInfo){
                $this->result([],-1,'404');
            }
            //获取用户基本信息（包括UnionID机制）
            $UserInfo = Wechat::userinfo($AuthorizeInfo['access_token'],$AuthorizeInfo['openid']);
        } catch(Exception $e){
//		    throw new Exception($e->getMessage(),-2);
		    $this->result(-1,$e->getMessage());
        }
//		print_r($AuthorizeInfo);

		$userModel = new User();
//        $user = $userModel->UnionidGetUser($AuthorizeInfo['unionid']);
        $user = $userModel->OpenidGetUser($AuthorizeInfo['openid']);
		//查询该用户是否注册过
		if(!$user){//如果没注册过
//            try{
//                //获取用户基本信息（包括UnionID机制）
//                $UserInfo = Wechat::userinfo($AuthorizeInfo['access_token'],$AuthorizeInfo['openid']);
//            } catch(Exception $e){
//                throw new Exception($e->getMessage(),-2);
//            }
			//新增用户
//			$id = $userModel->binduser($UserInfo['nickname'],$UserInfo['sex'],$UserInfo['headimgurl'],$UserInfo['openid'],$UserInfo['unionid']);
			$id = $userModel->binduser($UserInfo['nickname'],$UserInfo['sex'],$UserInfo['headimgurl'],$UserInfo['openid'],'');
			if(!$id){
				$this->result([],-1,'404');
			}
			//生成授权token
			$token = SUtil::createjwt(['time'=>time(),'user_id'=>$id,'nick_name'=>$UserInfo['nickname']]);
			return $this->result(['token'=>$token],1,'授权成功');
		}

		$res = $userModel->login($user['user_id'],$UserInfo['openid'],'wx_openid');
		if(!$res){
			$this->result([],-1,'404');
		}
		$token = SUtil::createjwt(['time'=>time(),'user_id'=>$user['user_id'],'nick_name'=>$user['nick_name']]);
		return $this->result(['token'=>$token],1,'授权成功');
	}

}
